package com.ruimei.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruimei.controller.LoginController;
import com.ruimei.entitys.Student;
import com.ruimei.mapper.UserMapper;
import com.ruimei.service.IParentService;
import com.ruimei.util.Base64Encoder;
import com.ruimei.util.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * @author Administrator
 */
@Component
public class LoginHandlerInterceptor
  implements  HandlerInterceptor
{

	@Resource
	private RedisTemplate<String,String> redisTemplate;

	@Resource
	private IParentService user;

	@Resource
	private UserMapper userMapper;


		@Override
	    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
			String id = null;
			String type = request.getHeader("type");
			String token = request.getHeader("token");
			System.out.println(type);
			if (type.equals("parent")) {
				if(request.getRequestURL().indexOf("loginByPass") != -1){
					 id = userMapper.queryParentByPhone(request.getParameter("phoneNo"));
					if(StringUtils.isBlank(id)){
						return true;
					}
				}
				else if(request.getRequestURL().indexOf("loginByPass") == -1 && StringUtils.isNotBlank(token)){
					id = TokenUtils.getParentId(request);
				}
				else{
					return false;
				}

				List<Student> students = userMapper.getStudents(id);
				if(students.size() == 0 ){
					return true;
				}
				boolean exists = false;
				int c = 0;
				for (Student student : students) {
					c++;
					if (student.getSecretkey().equals("1")) {
						return true;
					}
					if (c == students.size()&& !exists) {
						return reLogin(response, "由于您还未缴费,所以暂停使用本系统.");
					}

				}
			}

			if(StringUtils.isNotBlank(token)){
				return true;
			}

			return reLogin(response);
	    }

	    private boolean reLogin(HttpServletResponse response) throws IOException {
	        PrintWriter out;
	        try{
	        	JSONObject obj  = new JSONObject();
				response.setHeader("Content-type", "text/html;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				response.setStatus(401);
				obj.put("code","401");
	        	obj.put("msg","请先登录");
				obj.put("status",false);
	            out = response.getWriter();
	            out.append(JSON.toJSONString(obj));
	            return false;
	        } catch (Exception e){
	            e.printStackTrace();
	            response.sendError(500);
	            return false;
	        }
	    }

	private boolean reLogin(HttpServletResponse response,String message) throws IOException {
		PrintWriter out;
		try{
			JSONObject object  = new JSONObject();
			JSONObject obj  = new JSONObject();
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			obj.put("code","401");
			obj.put("msg",message);
			obj.put("status",false);

			object.put("status",true);
			object.put("data",obj);

			out = response.getWriter();
			out.write(JSON.toJSONString(object));

			return false;
		} catch (Exception e){
			e.printStackTrace();
			response.sendError(500);
			return false;
		}
	}

}
